<html><head><meta charset="utf-8"><title>15 类型兼容性，开放心态满足灵活的JS-慕课专栏</title>
			<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
			<meta name="renderer" content="webkit">
			<meta property="qc:admins" content="77103107776157736375">
			<meta property="wb:webmaster" content="c4f857219bfae3cb">
			<meta http-equiv="Access-Control-Allow-Origin" content="*">
			<meta http-equiv="Cache-Control" content="no-transform ">
			<meta http-equiv="Cache-Control" content="no-siteapp">
			<link rel="apple-touch-icon" sizes="76x76" href="https://www.imooc.com/static/img/common/touch-icon-ipad.png">
			<link rel="apple-touch-icon" sizes="120x120" href="https://www.imooc.com/static/img/common/touch-icon-iphone-retina.png">
			<link rel="apple-touch-icon" sizes="152x152" href="https://www.imooc.com/static/img/common/touch-icon-ipad-retina.png">
			<link href="https://moco.imooc.com/captcha/style/captcha.min.css" rel="stylesheet">
			<link rel="stylesheet" href="https://www.imooc.com/static/moco/v1.0/dist/css/moco.min.css?t=201907021539" type="text/css">
			<link rel="stylesheet" href="https://www.imooc.com/static/lib/swiper/swiper-3.4.2.min.css?t=201907021539">
			<link rel="stylesheet" href="https://static.mukewang.com/static/css/??base.css,common/common-less.css?t=2.5,column/zhuanlanChapter-less.css?t=2.5,course/inc/course_tipoff-less.css?t=2.5?v=201907051055" type="text/css">
			<link charset="utf-8" rel="stylesheet" href="https://www.imooc.com/static/lib/ueditor/themes/imooc/css/ueditor.css?v=201907021539"><link rel="stylesheet" href="https://www.imooc.com/static/lib/baiduShare/api/css/share_style0_16.css?v=6aba13f0.css"></head>
			<body><div id="main">

<div class="container clearfix" id="top" style="display: block; width: 1134px;">
    
    <div class="center_con js-center_con l" style="width: 1134px;">
        <div class="article-con">
                            <!-- 买过的阅读 -->
                <div class="map">
                    <a href="/read" target="_blank"><i class="imv2-feather-o"></i></a>
                    <a href="/read/35" target="_blank">零基础学透 TypeScript</a>
                    <a href="" target="_blank">
                        <span>
                            / 3-2 15 类型兼容性，开放心态满足灵活的JS
                        </span>
                    </a>
                </div>

            


            <div class="art-title" style="margin-top: 0px;">
                15 类型兼容性，开放心态满足灵活的JS
            </div>
            <div class="art-info">
                
                <span>
                    更新时间：2019-06-21 09:38:37
                </span>
            </div>
            <div class="art-top">
                                <img src="https://img4.mukewang.com/5d0b57de0001cfa106400359.jpg" alt="">
                                                <div class="famous-word-box">
                    <img src="https://www.imooc.com/static/img/column/bg-l.png" alt="" class="bg1 bg">
                    <img src="https://www.imooc.com/static/img/column/bg-r.png" alt="" class="bg2 bg">
                    <div class="famous-word">每个人都是自己命运的主宰。<p class="author">——斯蒂尔斯</p></div>
                </div>
                            </div>
            <div class="art-content js-lookimg">
                <div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们知道JavaScript是弱类型语言，它对类型是弱校验，正因为这个特点，所以才有了TypeScript这个强类型语言系统的出现，来弥补类型检查的短板。TypeScript在实现类型强校验的同时，还要满足JavaScript灵活的特点，所以就有了类型兼容性这个概念。本小节我们就来全面学习一下TypeScript的类型兼容性。</p>
</div><div class="cl-preview-section"><h3 id="函数兼容性">3.2.1 函数兼容性</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">函数的兼容性简单总结就是如下六点：</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><strong>(1) 函数参数个数</strong></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">函数参数个数如果要兼容，需要满足一个要求：<strong>如果对函数 y 进行赋值，那么要求 x 中的每个参数都应在 y 中有对应，也就是 x 的参数个数小于等于 y 的参数个数</strong>，来看例子：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">let</span> <span class="token function-variable function">x</span> <span class="token operator">=</span> <span class="token punctuation">(</span>a<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> <span class="token function-variable function">y</span> <span class="token operator">=</span> <span class="token punctuation">(</span>b<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">,</span> c<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token number">0</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">上面定义的两个函数，如果进行赋值的话，来看下两种情况的结果：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript">y <span class="token operator">=</span> x<span class="token punctuation">;</span> <span class="token comment">// 没问题</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">将 x 赋值给 y 是可以的，因为如果对函数 y 进行赋值，那么要求 x 中的每个参数都应在 y 中有对应，也就是 x 的参数个数小于等于 y 的参数个数，而至于参数名是否相同是无所谓的。</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript">x <span class="token operator">=</span> y<span class="token punctuation">;</span> <span class="token comment">// error Type '(b: number, s: string) =&gt; number' is not assignable to type '(a: number) =&gt; number'</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这个例子中，y 要赋值给 x，但是 y 的参数个数要大于 x，所以报错。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这可能不好理解，我们用另一个例子来解释下：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">const</span> arr <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
arr<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token punctuation">(</span>item<span class="token punctuation">,</span> index<span class="token punctuation">,</span> array<span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>item<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
arr<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span>item <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>item<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这个例子中，传给 forEach 的回调函数的参数是三个，但是可以只用一个，这样就只需写一个参数。我们传入的 forEach 的函数是 forEach 的参数，它是一个函数，这个函数的参数列表是定义在 forEach 方法内的，我们可以传入一个参数少于等于参数列表的函数，但是不能传入一个比参数列表参数个数还多的函数。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><strong>(2)函数参数类型</strong></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">除了参数个数，参数的类型需要对应：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">let</span> <span class="token function-variable function">x</span> <span class="token operator">=</span> <span class="token punctuation">(</span>a<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> <span class="token function-variable function">y</span> <span class="token operator">=</span> <span class="token punctuation">(</span>b<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> <span class="token function-variable function">z</span> <span class="token operator">=</span> <span class="token punctuation">(</span>c<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token keyword">false</span><span class="token punctuation">;</span>
x <span class="token operator">=</span> y<span class="token punctuation">;</span> <span class="token comment">// error 不能将类型“(b: string) =&gt; number”分配给类型“(a: number) =&gt; number”。</span>
x <span class="token operator">=</span> z<span class="token punctuation">;</span> <span class="token comment">// error 不能将类型“(c: string) =&gt; boolean”分配给类型“(a: number) =&gt; number”。</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们看到 x 和 y 两个函数的参数个数和返回值都相同，只是参数类型对不上，所以也是不行的。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">如果函数 z 想要赋值给 x，要求 y 的返回值类型必须是 x 的返回值类型的子类型，这个例子中 x 函数的返回值是联合类型，也就是返回值既可以是 string 类型也可以是 number 类型。而 y 的返回值类型是 number 类型，参数个数和类型也没问题，所以可以赋值给 x。而 z 的返回值类型 false 并不是 string 也不是 number，所以不能赋值。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><strong>(3)剩余参数和可选参数</strong></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">当要被赋值的函数参数中包含剩余参数（…args）时，赋值的函数可以用任意个数参数代替，但是类型需要对应。来看例子：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">const</span> getNum <span class="token operator">=</span> <span class="token punctuation">(</span> <span class="token comment">// 这里定义一个getNum函数，他有两个参数</span>
  arr<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token comment">// 第一个参数是一个数组</span>
  callback<span class="token punctuation">:</span> <span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token keyword">number</span> <span class="token comment">// 第二个参数是一个函数，这个函数的类型要求可以传入任意多个参数，但是类型必须是数值类型，返回值必须是数值类型</span>
<span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">number</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> <span class="token function">callback</span><span class="token punctuation">(</span><span class="token operator">...</span>arr<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 这个getNum函数直接返回调用传入的第二个参数这个函数，以第一个参数这个数组作为参数的函数返回值</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
<span class="token function">getNum</span><span class="token punctuation">(</span>
  <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
  <span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">number</span> <span class="token operator">=&gt;</span> args<span class="token punctuation">.</span>length <span class="token comment">// 这里传入一个函数，逻辑是返回参数的个数</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">剩余参数其实可以看做无数个可选参数，所以在兼容性方面是差不多的，我们来看个可选参数和剩余参数结合的例子：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">const</span> getNum <span class="token operator">=</span> <span class="token punctuation">(</span>
  arr<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
  callback<span class="token punctuation">:</span> <span class="token punctuation">(</span>arg1<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">,</span> arg2<span class="token operator">?</span><span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token keyword">number</span> <span class="token comment">// 这里指定第二个参数callback是一个函数，函数的第二个参数为可选参数</span>
<span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">number</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> <span class="token function">callback</span><span class="token punctuation">(</span><span class="token operator">...</span>arr<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// error 应有 1-2 个参数，但获得的数量大于等于 0</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这里因为arr可能为空数组或不为空，如果为空数组则…arr不会给callback传入任何实际参数，所以这里报错。如果我们换成<code>return callback(arr[0], …arr)</code>就没问题了。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><strong>(4) 函数参数双向协变</strong></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">函数参数双向协变即参数类型无需绝对相同，来看个例子：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">let</span> <span class="token function-variable function">funcA</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token punctuation">(</span>arg<span class="token punctuation">:</span> <span class="token keyword">number</span> <span class="token operator">|</span> <span class="token keyword">string</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">void</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> <span class="token function-variable function">funcB</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token punctuation">(</span>arg<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">void</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
<span class="token comment">// funcA = funcB 和 funcB = funcA都可以</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在这个例子中，funcA 和 funcB 的参数类型并不完全一样，funcA 的参数类型为一个联合类型 number | string，而 funcB 的参数类型为 number | string 中的 number，他们两个函数也是兼容的。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><strong>(5) 函数返回值类型</strong></p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">let</span> x <span class="token operator">=</span> <span class="token punctuation">(</span>a<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">string</span> <span class="token operator">|</span> <span class="token keyword">number</span> <span class="token operator">=&gt;</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> <span class="token function-variable function">y</span> <span class="token operator">=</span> <span class="token punctuation">(</span>b<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token string">"a"</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> <span class="token function-variable function">z</span> <span class="token operator">=</span> <span class="token punctuation">(</span>c<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token keyword">false</span><span class="token punctuation">;</span>
x <span class="token operator">=</span> y<span class="token punctuation">;</span>
x <span class="token operator">=</span> z<span class="token punctuation">;</span> <span class="token comment">// 不能将类型“(c: number) =&gt; boolean”分配给类型“(a: number) =&gt; string | number”</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><strong>(6) 函数重载</strong></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">带有重载的函数，要求被赋值的函数的每个重载都能在用来赋值的函数上找到对应的签名，来看例子：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">function</span> <span class="token function">merge</span><span class="token punctuation">(</span>arg1<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">,</span> arg2<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">;</span> <span class="token comment">// 这是merge函数重载的一部分</span>
<span class="token keyword">function</span> <span class="token function">merge</span><span class="token punctuation">(</span>arg1<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">,</span> arg2<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">;</span> <span class="token comment">// 这也是merge函数重载的一部分</span>
<span class="token keyword">function</span> <span class="token function">merge</span><span class="token punctuation">(</span>arg1<span class="token punctuation">:</span> <span class="token keyword">any</span><span class="token punctuation">,</span> arg2<span class="token punctuation">:</span> <span class="token keyword">any</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment">// 这是merge函数实体</span>
  <span class="token keyword">return</span> arg1 <span class="token operator">+</span> arg2<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">function</span> <span class="token function">sum</span><span class="token punctuation">(</span>arg1<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">,</span> arg2<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">;</span> <span class="token comment">// 这是sum函数重载的一部分</span>
<span class="token keyword">function</span> <span class="token function">sum</span><span class="token punctuation">(</span>arg1<span class="token punctuation">:</span> <span class="token keyword">any</span><span class="token punctuation">,</span> arg2<span class="token punctuation">:</span> <span class="token keyword">any</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">any</span> <span class="token punctuation">{</span> <span class="token comment">// 这是sum函数实体</span>
  <span class="token keyword">return</span> arg1 <span class="token operator">+</span> arg2<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">let</span> func <span class="token operator">=</span> merge<span class="token punctuation">;</span>
func <span class="token operator">=</span> sum<span class="token punctuation">;</span> <span class="token comment">// error 不能将类型“(arg1: number, arg2: number) =&gt; number”分配给类型“{ (arg1: number, arg2: number): number; (arg1: string, arg2: string): string; }”</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">上面例子中，sum函数的重载缺少参数都为string返回值为string的情况，与merge函数不兼容，所以赋值时会报错。</p>
</div><div class="cl-preview-section"><h3 id="枚举">3.2.2 枚举</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">数字枚举成员类型与数字类型互相兼容，来看例子：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">enum</span> Status <span class="token punctuation">{</span>
  On<span class="token punctuation">,</span>
  Off
<span class="token punctuation">}</span>
<span class="token keyword">let</span> s <span class="token operator">=</span> Status<span class="token punctuation">.</span>On<span class="token punctuation">;</span>
s <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
s <span class="token operator">=</span> <span class="token number">3</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">虽然Status.On的值是0，但是这里数字枚举成员类型和数值类型互相兼容，所以这里给s赋值为3也没问题。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">但是不同枚举值之间是不兼容的：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">enum</span> Status <span class="token punctuation">{</span>
  On<span class="token punctuation">,</span>
  Off
<span class="token punctuation">}</span>
<span class="token keyword">enum</span> Color <span class="token punctuation">{</span>
  White<span class="token punctuation">,</span>
  Black
<span class="token punctuation">}</span>
<span class="token keyword">let</span> s <span class="token operator">=</span> Status<span class="token punctuation">.</span>On<span class="token punctuation">;</span>
s <span class="token operator">=</span> Color<span class="token punctuation">.</span>White<span class="token punctuation">;</span> <span class="token comment">// error Type 'Color.White' is not assignable to type 'Status'</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">可以看到，虽然 Status.On 和 Color.White 的值都是 0，但它们是不兼容的。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">字符串枚举成员类型和字符串类型是不兼容的，来看例子：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">enum</span> Status <span class="token punctuation">{</span>
  On <span class="token operator">=</span> <span class="token string">'on'</span><span class="token punctuation">,</span>
  Off <span class="token operator">=</span> <span class="token string">'off'</span>
<span class="token punctuation">}</span>
<span class="token keyword">let</span> s <span class="token operator">=</span> Status<span class="token punctuation">.</span>On
s <span class="token operator">=</span> <span class="token string">'Lison'</span> <span class="token comment">// error 不能将类型“"Lison"”分配给类型“Status”</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这里会报错，因为字符串字面量类型<code>'Lison'</code>和Status.On是不兼容的。</p>
</div><div class="cl-preview-section"><h3 id="类">3.2.3 类</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><strong>基本比较</strong></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">比较两个类类型的值的兼容性时，只比较实例的成员，类的静态成员和构造函数不进行比较：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">class</span> <span class="token class-name">Animal</span> <span class="token punctuation">{</span>
  <span class="token keyword">static</span> age<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">;</span>
  <span class="token keyword">constructor</span><span class="token punctuation">(</span><span class="token keyword">public</span> name<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">class</span> <span class="token class-name">People</span> <span class="token punctuation">{</span>
  <span class="token keyword">static</span> age<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">;</span>
  <span class="token keyword">constructor</span><span class="token punctuation">(</span><span class="token keyword">public</span> name<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">class</span> <span class="token class-name">Food</span> <span class="token punctuation">{</span>
  <span class="token keyword">constructor</span><span class="token punctuation">(</span><span class="token keyword">public</span> name<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">let</span> a<span class="token punctuation">:</span> Animal<span class="token punctuation">;</span>
<span class="token keyword">let</span> p<span class="token punctuation">:</span> People<span class="token punctuation">;</span>
<span class="token keyword">let</span> f<span class="token punctuation">:</span> Food<span class="token punctuation">;</span>
a <span class="token operator">=</span> p<span class="token punctuation">;</span> <span class="token comment">// right</span>
a <span class="token operator">=</span> f<span class="token punctuation">;</span> <span class="token comment">// error Type 'Food' is not assignable to type 'Animal'</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">上面例子中，Animal类和People类都有一个age静态属性，它们都定义了实例属性name，且name的类型都是string。我们看到把类型为People的p赋值给类型为Animal的a没有问题，因为我们讲了，类类型比较兼容性时，只比较实例的成员，这两个变量虽然类型是不同的类类型，但是它们都有相同字段和类型的实例属性name，而类的静态成员是不影响兼容性的，所以它俩兼容。而类Food定义了一个实例属性name，类型为number，所以类型为Food的f与类型为Animal的a类型不兼容，不能赋值。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><strong>类的私有成员和受保护成员</strong></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">类的私有成员和受保护成员会影响兼容性。当检查类的实例兼容性时，如果目标（也就是要被赋值的那个值）类型（这里实例类型就是创建它的类）包含一个私有成员，那么源（也就是用来赋值的值）类型必须包含来自同一个类的这个私有成员，这就允许子类赋值给父类。先来看例子：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">class</span> <span class="token class-name">Parent</span> <span class="token punctuation">{</span>
  <span class="token keyword">private</span> age<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">;</span>
  <span class="token keyword">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">class</span> <span class="token class-name">Children</span> <span class="token keyword">extends</span> <span class="token class-name">Parent</span> <span class="token punctuation">{</span>
  <span class="token keyword">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">super</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">class</span> <span class="token class-name">Other</span> <span class="token punctuation">{</span>
  <span class="token keyword">private</span> age<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">;</span>
  <span class="token keyword">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">const</span> children<span class="token punctuation">:</span> Parent <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Children</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> other<span class="token punctuation">:</span> Parent <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Other</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 不能将类型“Other”分配给类型“Parent”。类型具有私有属性“age”的单独声明</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">可以看到，当指定 other 为 Parent 类类型，给 other 赋值 Other 创建的实例的时候，会报错。因为 Parent 的 age 属性是私有成员，外界是无法访问到的，所以会类型不兼容。而children的类型我们指定为了Parent类类型，然后给它赋值为Children类的实例，没有问题，是因为Children类继承Parent类，且实例属性没有差异，Parent类有私有属性age，但是因为Children类继承了Parent类，所以可以赋值。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">同样，使用 protected 受保护修饰符修饰的属性，也是一样的。</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">class</span> <span class="token class-name">Parent</span> <span class="token punctuation">{</span>
  <span class="token keyword">protected</span> age<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">;</span>
  <span class="token keyword">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">class</span> <span class="token class-name">Children</span> <span class="token keyword">extends</span> <span class="token class-name">Parent</span> <span class="token punctuation">{</span>
  <span class="token keyword">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">super</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">class</span> <span class="token class-name">Other</span> <span class="token punctuation">{</span>
  <span class="token keyword">protected</span> age<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">;</span>
  <span class="token keyword">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">const</span> children<span class="token punctuation">:</span> Parent <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Children</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> other<span class="token punctuation">:</span> Parent <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Other</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 不能将类型“Other”分配给类型“Parent”。属性“age”受保护，但类型“Other”并不是从“Parent”派生的类</span>
</code></pre>
</div><div class="cl-preview-section"><h3 id="泛型">3.2.4 泛型</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">泛型包含类型参数，这个类型参数可能是任意类型，使用时类型参数会被指定为特定的类型，而这个类型只影响使用了类型参数的部分。来看例子：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">interface</span> <span class="token class-name">Data</span><span class="token operator">&lt;</span>T<span class="token operator">&gt;</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token keyword">let</span> data1<span class="token punctuation">:</span> Data<span class="token operator">&lt;</span><span class="token keyword">number</span><span class="token operator">&gt;</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> data2<span class="token punctuation">:</span> Data<span class="token operator">&lt;</span><span class="token keyword">string</span><span class="token operator">&gt;</span><span class="token punctuation">;</span>

data1 <span class="token operator">=</span> data2<span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在这个例子中，data1 和 data2 都是 Data 接口的实现，但是指定的泛型参数的类型不同，TS 是结构性类型系统，所以上面将 data2 赋值给 data1 是兼容的，因为 data2 指定了类型参数为 string 类型，但是接口里没有用到参数 T，所以传入 string 类型还是传入 number 类型并没有影响。我们再来举个例子看下：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">interface</span> <span class="token class-name">Data</span><span class="token operator">&lt;</span>T<span class="token operator">&gt;</span> <span class="token punctuation">{</span>
  data<span class="token punctuation">:</span> T<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">let</span> data1<span class="token punctuation">:</span> Data<span class="token operator">&lt;</span><span class="token keyword">number</span><span class="token operator">&gt;</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> data2<span class="token punctuation">:</span> Data<span class="token operator">&lt;</span><span class="token keyword">string</span><span class="token operator">&gt;</span><span class="token punctuation">;</span>

data1 <span class="token operator">=</span> data2<span class="token punctuation">;</span> <span class="token comment">// error 不能将类型“Data&lt;string&gt;”分配给类型“Data&lt;number&gt;”。不能将类型“string”分配给类型“number”</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">现在结果就不一样了，赋值时报错，因为 data1 和 data2 传入的泛型参数类型不同，生成的结果结构是不兼容的。</p>
</div><div class="cl-preview-section"><h3 id="本节小结">本节小结</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">本小节我们学习了TypeScript的类型兼容性，学习了各种情况下赋值的可行性。这里面函数的兼容性最为复杂，能够影响函数兼容性的因素有：</p>
</div><div class="cl-preview-section"><ul>
<li style="font-size: 20px; line-height: 38px;">函数参数个数： 如果对函数 y 进行赋值，那么要求 x 中的每个参数都应在 y 中有对应，也就是 x 的参数个数小于等于 y 的参数个数；</li>
<li style="font-size: 20px; line-height: 38px;">函数参数类型： 这一点其实和基本的赋值兼容性没差别，只不过比较的不是变量之间而是参数之间；</li>
<li style="font-size: 20px; line-height: 38px;">剩余参数和可选参数： 当要被赋值的函数参数中包含剩余参数（…args）时，赋值的函数可以用任意个数参数代替，但是类型需要对应，可选参数效果相似；</li>
<li style="font-size: 20px; line-height: 38px;">函数参数双向协变： 即参数类型无需绝对相同；</li>
<li style="font-size: 20px; line-height: 38px;">函数返回值类型： 这一点和函数参数类型的兼容性差不多，都是基础的类型比较；</li>
<li style="font-size: 20px; line-height: 38px;">函数重载： 要求被赋值的函数每个重载都能在用来赋值的函数上找到对应的签名。</li>
</ul>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">枚举较为简单，数字枚举成员类型与数值类型兼容，字符串枚举成员与字符串类型不兼容。类的兼容性比较的主要依据是实例成员，但是私有成员和受保护成员也会影响兼容性。最后是涉及到泛型的类型兼容性，一定要记住一点的是<strong>使用时指定的特定类型只会影响使用了类型参数的部分</strong>。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">下个小节我们学习类型保护，还记得前面讲TS中补充的六个类型和类型断言的时候，都提到过类型保护，使用类型保护，可以明确告诉编译器某个值是某种类型，虽然听起来和类型断言一样，但是它要比类型断言更便捷，我们下节课来进行详细学习。<br>
<img src="http://img.mukewang.com/5d034278000130c116000890.jpg" alt="图片描述" data-original="http://img.mukewang.com/5d034278000130c116000890.jpg" class="" style="cursor: pointer;"></p>
</div></div>
            </div>
                            <!-- 买过的阅读 -->
                <div class="art-next-prev clearfix">
                                                                        <!-- 已买且开放 或者可以试读 -->
                            <a href="/read/35/article/351">
                                                    <div class="prev l clearfix">
                                <div class="icon l">
                                    <i class="imv2-arrow3_l"></i>
                                </div>
                                <p>
                                    14 类型推论，看TS有多懂你
                                </p>
                            </div>
                        </a>
                                                                                            <!-- 已买且开放 或者可以试读 -->
                            <a href="/read/35/article/353">
                                                    <div class="next r clearfix">
                                <p>
                                    16 使用类型保护让TS更聪明
                                </p>
                                <div class="icon r">
                                    <i class="imv2-arrow3_r"></i>
                                </div>

                            </div>
                        </a>
                                    </div>
                    </div>
        <div class="comments-con js-comments-con" id="coments_con">     <div class="number">精选留言 <span class="js-number">0</span></div>     <div class="comments">         <div class="input-fake js-showcommentModal">             欢迎在这里发表留言，作者筛选后可公开显示         </div>                      <div class="noData">                 <p>                     <i class="imv2-error_c"></i>                 </p>                 <p>目前暂无任何讨论</p>             </div>              </div>  </div>



    </div>
    
    
    

</div>
 
<!-- 专栏介绍页专栏评价 -->

<!-- 专栏介绍页底部三条评价 -->

<!-- 专栏阅读页弹层目录和介绍页页面目录 -->

<!-- 专栏阅读页发布回复 -->

<!-- 专栏阅读页发布评论 -->

<!-- 专栏阅读页底部评论 -->

<!-- 专栏阅读 单个 评论 -->

<!-- 新增回复和展开三条以外回复 -->

<!-- 立即订阅的弹窗 -->












</div></body></html>